from flask import Blueprint, request, jsonify, Response, stream_with_context, render_template
from openai import OpenAI
from dotenv import load_dotenv
import os

load_dotenv('.env')


aiapi = Blueprint("openai",__name__)
url_prefix = '/ai'

client = OpenAI(
    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
    api_key= os.getenv('API_KEY'), # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
# 通过 messages 数组实现上下文管理
messages = [
    {'role': 'system', 'content':  '''When asked about the meaning of table fields, please use a JSON object instead of using the markdown syntax. 
    For example, what does the table field 'account' mean? Reply: {"account": "account"}. 
    If it does not include 'account', there is no need to return the 'account' attribute.
    All questions except for table fields are answered using the default format.
    '''}
]


@aiapi.route("/chat",methods=["post"])
@stream_with_context
def ai_chat():
    token = request.json.get('token')
    content = request.json.get('content')
    if content is None:
        return jsonify({"code":2,"msg":'content is None'})
    messages.append({'role': 'user', 'content':  content})
    # print(content)
    completion = client.chat.completions.create(
        model="qwen-plus",  # 此处以 deepseek-r1 为例，可按需更换模型名称。
        messages=messages,
        stream=True,
        stream_options={"include_usage": True},
    )
    def read_stream ():
        is_answering = False  # 判断是否结束思考过程并开始回复
        for chunk in completion:
            # 如果chunk.choices为空，则打印usage
            if not chunk.choices:
                print("\nUsage:")
                print(chunk.usage)
            else:
                delta = chunk.choices[0].delta
                print(delta)
                # 打印思考过程
                if hasattr(delta, 'reasoning_content') and delta.reasoning_content != None:
                    print(delta.reasoning_content, end='', flush=True)
                else:
                    # 开始回复
                    if delta.content != "" and is_answering == False:
                        print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
                        is_answering = True
                    # 打印回复过程
                    yield delta.content

    # messages.append({'role': 'assistant', 'content': completion.choices[0].message.content})
    # print(completion.choices[0].message)
    return Response(read_stream())
